package com.cyandpos.pad.cateringformat.opentable;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.changyi.device.APApplication;
import com.cyandpos.pad.R;
import com.cyandpos.pad.activity.MainActivity;
import com.cyandpos.pad.cateringformat.BaseFragment;
import com.cyandpos.pad.cateringformat.choosemenu.MenuFoodActivity;
import com.cyandpos.pad.common.commondata.CateringPosConstant;
import com.cyandpos.pad.common.commondata.ConstantString;
import com.cyandpos.pad.common.commondata.DialogConstant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.commondata.OnDialogListener;
import com.cyandpos.pad.cateringformat.morefunction.adapter.OrderFoodtableInfoAdapter;
import com.cyandpos.pad.posdata.DinnerTable;
import com.cyandpos.pad.posdata.Sktconfig;
import com.cyandpos.pad.posdata.TableReserve;
import com.cyandpos.pad.sale.saleutils.SaleUtil;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by xin on 2021/8/30
 * desc: 开台界面
 */
public class OpenTableFragment extends BaseFragment implements View.OnClickListener,ImplViewFragmentOpenTable {

    @BindView(R.id.gv_act_openTable)
    GridView gvActOpenTable;
    @BindView(R.id.btn_act_allStatus_openTable)
    Button btnActAllStatusOpenTable;
    @BindView(R.id.btn_act_fullStatus_openTable)
    Button btnActFullStatusOpenTable;
    @BindView(R.id.btn_act_useStatus_openTable)
    Button btnActUseStatusOpenTable;
    @BindView(R.id.btn_act_usedStatus_openTable)
    Button btnActUsedStatusOpenTable;
    @BindView(R.id.btn_act_scheduledStatus_openTable)
    Button btnActScheduledStatusOpenTable;
    @BindView(R.id.btn_act_deadStatus_openTable)
    Button btnActDeadStatusOpenTable;
    @BindView(R.id.btn_act_refresh_openTable)
    Button btnActRefreshOpenTable;
    Unbinder unbinder;

    OpenTableGridAdapter adapter;
    private int tableStatusIndex = CateringPosConstant.CATERING_TABLE_STATUS_ALL;
    private List<DinnerTable> adapterList;
    public  AlertDialog mDialog;

    private ProgressDialog mProgressDialog;//等待框

    PresentFragmentOpenTable mPresent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_open_table_main, container, false);
        unbinder = ButterKnife.bind(this, view);
        initData();
        return view;
    }

    private void initData() {
        mPresent = new PresentFragmentOpenTable(this);
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setCancelable(false);
        adapterList = new ArrayList<>();
        adapterList.addAll(ErpCommonData.loadConfig.getTableList());
        adapter = new OpenTableGridAdapter(getActivity(),adapterList);
        gvActOpenTable.setAdapter(adapter);
        initListenter();
        initTableStatusBtn(CateringPosConstant.CATERING_TABLE_STATUS_ALL);
        gvActOpenTable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                DinnerTable tableItem = (DinnerTable) adapterList.get(position);
                if(tableItem !=null){
                    if(tableItem.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_FULL
                    ){
                        showInputInfoDialog(tableItem);
                    }else if(tableItem.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_USE){
                        startMenuFoodActivity("",tableItem);
                    }else if(tableItem.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_USED){
                        clearTableStateDialog(tableItem);
                    }
                }else{
                    ToastUtils.show("点击对象为空！");
                }

            }
        });
        gvActOpenTable.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                DinnerTable tableItem = (DinnerTable) adapterList.get(position);
                if(tableItem.getTableReserveList()!=null && tableItem.getTableReserveList().size()>0){
                    mPresent.queryTableReserveInfo(tableItem.getId());
                }else{
                    ToastUtils.show("当前餐桌【"+tableItem.getId()+"】没有预定信息！");
                }
                return true;
            }
        });
    }

    private void clearTableStateDialog(final DinnerTable tableItem) {
        SaleUtil.showInfoDialog(getActivity(),
                "脏桌操作",
               "桌号【"+tableItem.getId()+"】，是否清桌？",
                new OnDialogListener() {
                    @Override
                    public void onClick(int flag) {
                        if(flag == DialogConstant.DIALOG_BTN_SURE){
                            mPresent.clearTableStatus(tableItem.getId(),CateringPosConstant.CATERING_TABLE_STATUS_FULL);
                        }
                    }
                });
    }


    public void  showInputInfoDialog(final DinnerTable tableItem) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_input_people_info, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        tvTitle.setText("请输入就餐人数");
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });

        final EditText et_people = view.findViewById(R.id.et_open_table_people);//就餐人数

        final SelfNumKeyView sf_containt = view.findViewById(R.id.open_table_soft_keyboard);

        et_people.setFocusable(false);
        sf_containt.setEnterReceptor(et_people);
        et_people.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sf_containt.setEnterReceptor(et_people);
                CommonUtils.hideSoftInputButWithSelection(et_people,getActivity());
                et_people.setFocusable(true);
                et_people.setFocusableInTouchMode(true);
                et_people.requestFocus();
            }
        });

        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                mDialog.dismiss();
                if(Integer.parseInt(num)>tableItem.getSize()){
                   ToastUtils.show("人数超出！");
                }else {
                    startMenuFoodActivity(num, tableItem);
                }
            }
        });
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setView(view).setCancelable(false).create();
        mDialog = dialog.show();

    }

    private void startMenuFoodActivity(String num, DinnerTable tableItem) {
        Intent intent=new Intent(getActivity(), MenuFoodActivity.class);
        if(CommonUtils.isNullOrEmpty(num)){
            intent.putExtra("tablePerson","1");
        }else{
            intent.putExtra("tablePerson",num+"");
        }
        intent.putExtra("tableNo",tableItem.getId()+"");
        intent.putExtra("tableState",tableItem.getStatus());
        intent.putExtra("fromType",1);//中餐
        startActivity(intent);
    }

    private void initListenter() {
        btnActAllStatusOpenTable.setOnClickListener(this);
        btnActFullStatusOpenTable.setOnClickListener(this);
        btnActUseStatusOpenTable.setOnClickListener(this);
        btnActUsedStatusOpenTable.setOnClickListener(this);
        btnActScheduledStatusOpenTable.setOnClickListener(this);
        btnActDeadStatusOpenTable.setOnClickListener(this);
        btnActRefreshOpenTable.setOnClickListener(this);
    }

    private void initTableStatusBtn(int count) {
        btnActAllStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_ALL ?
                                            getResources().getColor(R.color.main_good_info_bar) :getResources().getColor(R.color.white));
        btnActFullStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_FULL ?
                                            getResources().getColor(R.color.main_good_info_bar):getResources().getColor(R.color.white));
        btnActUseStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_USE ?
                                            getResources().getColor(R.color.main_good_info_bar):getResources().getColor(R.color.white));
        btnActUsedStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_USED ?
                                            getResources().getColor(R.color.main_good_info_bar):getResources().getColor(R.color.white));
        btnActScheduledStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_SCHEDULED ?
                                            getResources().getColor(R.color.main_good_info_bar):getResources().getColor(R.color.white));
        btnActDeadStatusOpenTable.setBackgroundColor(count==CateringPosConstant.CATERING_TABLE_STATUS_STOP ?
                                            getResources().getColor(R.color.main_good_info_bar):getResources().getColor(R.color.white));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_act_allStatus_openTable:
                tableStatusIndex= CateringPosConstant.CATERING_TABLE_STATUS_ALL;
                break;
            case R.id.btn_act_fullStatus_openTable:
                tableStatusIndex=CateringPosConstant.CATERING_TABLE_STATUS_FULL;
                break;
            case R.id.btn_act_useStatus_openTable:
                tableStatusIndex=CateringPosConstant.CATERING_TABLE_STATUS_USE;
                break;
            case R.id.btn_act_usedStatus_openTable:
                tableStatusIndex=CateringPosConstant.CATERING_TABLE_STATUS_USED;
                break;
            case R.id.btn_act_scheduledStatus_openTable:
                tableStatusIndex=CateringPosConstant.CATERING_TABLE_STATUS_SCHEDULED;
                break;
            case R.id.btn_act_deadStatus_openTable:
                tableStatusIndex=CateringPosConstant.CATERING_TABLE_STATUS_STOP;
                break;
            case R.id.btn_act_refresh_openTable:
                updateDinnerTableStatus();
                break;

        }
        initTableStatusBtn(tableStatusIndex);
        refreshTablesList(tableStatusIndex);
    }

    private void refreshTablesList(int tableStatusIndex) {
        adapterList.clear();
        if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_ALL){
            adapterList.addAll(ErpCommonData.loadConfig.getTableList());
        }else if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_FULL){
            for(DinnerTable item :ErpCommonData.loadConfig.getTableList()){
                if(item.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_FULL){
                    adapterList.add(item);
                }
            }
        }else if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_USE){
            for(DinnerTable item :ErpCommonData.loadConfig.getTableList()){
                if(item.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_USE){
                    adapterList.add(item);
                }
            }
        }else if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_USED){
            for(DinnerTable item :ErpCommonData.loadConfig.getTableList()){
                if(item.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_USED){
                    adapterList.add(item);
                }
            }
        }else if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_SCHEDULED){
            for(DinnerTable item :ErpCommonData.loadConfig.getTableList()){
                if(item.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_SCHEDULED){
                    adapterList.add(item);
                }
            }
        }else if(tableStatusIndex == CateringPosConstant.CATERING_TABLE_STATUS_STOP){
            for(DinnerTable item :ErpCommonData.loadConfig.getTableList()){
                if(item.getStatus() == CateringPosConstant.CATERING_TABLE_STATUS_STOP){
                    adapterList.add(item);
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showProgress(String msg) {
        mProgressDialog.setMessage(msg);
        mProgressDialog.show();
    }

    @Override
    public void dismissProgress() {
        mProgressDialog.dismiss();
    }


    /**
     * 刷新餐桌状态
     * @param tableList 餐桌列表
     */
    @Override
    public void refreshDinnerTableInfo(List<DinnerTable> tableList) {
        adapterList.clear();
        adapterList.addAll(tableList);
        adapter.notifyDataSetChanged();
        ErpCommonData.loadConfig.setTableList(tableList);
        initTableStatusBtn(CateringPosConstant.CATERING_TABLE_STATUS_ALL);
    }

    /**
     * 显示预定详情
     * @param tableReserveList
     */
    @Override
    public void showDinnerTableReserveInfo(List<TableReserve> tableReserveList) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.activity_order_food_info, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        ListView lv_reserve = view.findViewById(R.id.lis_act_ordertable);
        tvTitle.setText("款台预定详情");
        tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        OrderFoodtableInfoAdapter adapter = new OrderFoodtableInfoAdapter(getActivity(),tableReserveList);
        lv_reserve.setAdapter(adapter);
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        dialog.setView(view).setCancelable(false).create();
        mDialog = dialog.show();

    }

    @Override
    public void clearDinnerTableSuccess() {
        ToastUtils.show("更新餐桌状态成功！");
        updateDinnerTableStatus();
    }
    @Override
    public void requestNetFail(String msg) {
        ToastUtils.show(msg);
    }

    public void updateDinnerTableStatus(){
        if(mPresent!=null)
          mPresent.queryTableStatusInfo(-1);
    }
}
